<template>
    <div class="mb-wrap" v-loading="loading">
        <!--<div class="mb-tree-wrap">-->
        <perfect-scrollbar class="mb-tree" :settings="{}" @click="handleClearSelect()">
            <el-tree ref="menutree"
                     class="menu-custom-tree"
                     :data="items"
                     node-key="tid"
                     :highlight-current="true"
                     :expand-on-click-node="false"
                     :default-expanded-keys="expandedKeys"
                     :props="treeSetting"
                     draggable
                     @node-drop="handleDragDrop"

                     @click.native.stop="empty"
                     @node-click="handleClick" style="min-height: 300px;">
                <span class="menu-custom-tree-node menu-icon-node" slot-scope="{ node, data }">
                    <span class="menu-custom-icon" :class="{ 'is-app': isApp(data), 'is-empty': isGroup(data) }"
                          :style="getIconStyle(data)">
                        <i v-if="data.loading" class="el-icon-loading"></i>
                        <img v-else-if="isGroup(data)" :src="getIconDefault(data)" />
                        <img v-else-if="getIconImg(data)" :src="getIconImg(data)" />
                        <!--<i v-else-if="getIconFont(data)" :class="getIconFont(data)"></i>-->
                        <template v-else-if="getIconFont(data)">
                            <i class="menu-icon-white" :class="getIconFont(data)"></i>
                            <i class="menu-icon-color" :class="getIconFont(data)"></i>
                        </template>
                        <img v-else :src="getIconDefault(data)" />
                    </span>
                    <span v-text="data.name"></span>
                    <i v-if="isApp(data)" class="app-icon fa fa-app-store" v-tippy="{ arrow: true }" content="应用"></i>
                    <!-- fa-creative-commons-pd -->
                    <i v-if="isWhite(data)" class="app-icon fa fa-weebly" v-tippy="{ arrow: true }" content="白名单菜单"></i>
                    <!--<i class="el-icon-arrow-up btn-up" @click.stop="handleMenuUp(data)"></i>
                    <i class="el-icon-arrow-down btn-down" @click.stop="handleMenuDown(data)"></i>-->
                </span>
            </el-tree>
        </perfect-scrollbar>
        <!--</div>-->
        <div class="mb-info">

        </div>
    </div>
</template>

<script>
    import { mapState, mapActions } from 'vuex';

    import common from '../../../common/common';

    const DEFAULT_FORM = {
        content_type: 'NORMAL',
        content_name: "",
        content_code: "",
        content_desc: "",
        icon: '',
        form_id: -1,
        flow_id: -1,
        arg0: '',
        is_default_menu: 0,

        group_code: '',
        group_name: '',
        group_desc: '',
        flow: { flow_id: '', flow_name: '' },
        form: { form_id: '', form_name: '' },
        view: { form_view_id: '', view_name: '' },
        page_id: null,
        page: { page_id: '', page_name: '' }
    }

    export default {
        props: {
            tty: {
                type: Number,
                default: 1
            },
            appId: Number
        },
        data() {
            return {
                winName: '新增',
                items: [],
                loading: false,
                currentData: {},
                groups: [],
                contents: [],

                actionType: 'view',     // createGroup | createMenu | edit | view
                form: _.cloneDeep(DEFAULT_FORM),
                rules: {
                    name: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' }
                    ]
                },
                expandedKeys: [],
                // checkedKeys: [],
                treeSetting: {
                    children: 'subs',
                    label: 'name',
                    'icon-class': 'hello-icon'
                },

                currentNode: null,
                currentResolve: null,

                // showFormSelectWin: false,
                formSelectWinName: '选择表单'
            }
        },
        components: {

        },
        created () {
            // this.pid = this.$route.query.pid;
        },
        mounted () {
            this.init();
        },
        watch: {
            '$route' (to, from) {
                // this.groupId = this.$route.params.groupId;
                // this.refresh();
            },
            'selectedMenus'(val) {
                // console.log(`======> selectedMenus: ` + val);
            },
            appId() {
                this.init();
            },
            tty() {
                this.init();
            }
        },
        filters: {
            viewLabel(view) {
                return (view && view.view_name) || '默认';
            }
        },
        computed: {
            ...mapState([
                'loginUser',
                'project'
            ]),
            canEdit() {
                let editing = true;

                if(this.currentData && this.currentData.project_id == -1) {
                    if(this.loginUser.type == '_SUPER') {
                        editing = true;
                    } else {
                        editing = false;
                    }
                }

                return editing;
            }
        },
        methods: {
            ...common,
            async init() {
                let menutree;

                this.loading = true;

                if(this.appId) {
                    menutree = await this.$japi.menu.getSubMenuTree(this.appId, this.tty);
                } else {
                    menutree = await this.$japi.menu.getMenuTree(this.tty);
                }

                this.items = menutree || [];
                this.currentData = null;
                // 默认展开一级菜单
                this.expandedKeys = _.map(menutree, 'tid');

                this.loading = false;
            },

            close(flag) {
                this.$emit('close', flag);
            },
            empty: function() {},
            async refreshCurrentNode(tid) {
                await this.init();

                if(!tid) {
                    return;
                }
                let paths = this.$utils.getTreePath(tid, this.items, 'tid', 'subs', true);
                let info = _.find(paths, { tid: tid });

                console.log(tid);
                console.log(this.items);
                console.log(_.map(paths, 'tid'));

                this.expandedKeys = _.map(paths, 'tid');
                this.handleClick(info);
            },
            async refreshParentNode(dt) {

                let isMbGroup = this._isGroup(dt);
                let parent_id = null;
                if(isMbGroup) {
                    parent_id = _.get(dt, 'parent_id');
                } else {
                    parent_id = _.get(dt, 'content_group_id');
                }

                console.log(dt);
                console.log(parent_id)

                if(!parent_id) return;

                let tid = `g_${parent_id}`;

                this.refreshCurrentNode(tid);
            },
            handleClick(data, node, ele) {
                // this.chooseNode(data);
                this.actionType = 'view';
                this.currentData = data;
                this.form = _.cloneDeep(this.currentData);

                if(this.$refs.menutree.store.nodesMap && this.$refs.menutree.store.nodesMap[ data.tid ]) {
                    this.$refs.menutree.store.nodesMap[ data.tid ].expanded = true;
                }
            },
            handleClearSelect() {
                try {
                    this.$refs.menutree.setCurrentNode({ tid: null });
                } catch(e) {
                    // e.message
                }

                this.currentData = {};
                this.form = _.clone(DEFAULT_FORM);
            },
            _isGroup(data) {
                return !!_.get(data, 'group_id') && !_.get(data, 'content_id');
            },
            _isVE() {
                return this.actionType == 'edit' || this.actionType == 'view';
            },
            isGroup(data) {
                return this._isGroup(data) && _.get(data, 'type') === 1
            },
            isMenu(data) {
                return !!_.get(data, 'content_id');
            },
            isApp(data) {
                return this._isGroup(data) && _.get(data, 'type') === 2;
            },
            isWhite(data) {
                return data && data.is_white_menu === 1;
            },
            isSelected(data) {
                return this.isGroup(data) || this.isMenu(data) || this.isApp(data);
            },
            isGroupForm() {
                return this.actionType == 'createGroup' || (this._isVE() && this.isGroup(this.currentData));
                /** && (this.actionType == 'edit' || this.actionType == 'view') **/
            },
            isMenuForm() {
                return this.actionType == 'createMenu' || (this._isVE() && this.isMenu(this.currentData));
                /** && (this.actionType == 'edit' || this.actionType == 'view') **/
            },
            isAppForm() {
                return this.actionType == 'createApp' || (this._isVE() && this.isApp(this.currentData));
                /**  && (this.actionType == 'edit' || this.actionType == 'view') **/
            },
            handleShowCreateGroup() {
                this.actionType = 'createGroup';     // createGroup | createMenu | edit | view

                if(!this.isGroup(this.currentData)) {
                    return;
                }
            },
            handleShowCreateApp() {
                this.actionType = 'createApp';     // createGroup | createMenu | edit | view

                if(!this.isGroup(this.currentData)) {
                    return;
                }
            },
            handleShowCreateMenu() {
                this.actionType = 'createMenu';
            },
            handleShowEdit() {
                this.actionType = 'edit';
            },
            async handleShowDelete() {

                let dt = this.currentData;

                if(!dt) {
                    return;
                }

                let isMbGroup = this._isGroup(dt);
                let msg = `确定删除${ isMbGroup ? '分组': '菜单' }【${dt.name}】?`;
                this.$confirm(msg, '删除确认').then(async () => {
                    let id = dt.id;
                    let ret = null;

                    if(isMbGroup) {
                        ret = await this.$japi.group.removeGroup(id);
                    } else {
                        ret = await this.$japi.menu.removeMenu(id);
                    }

                    if(!ret) {
                        return;
                    }

                    let parent_id = null;

                    if(isMbGroup) {
                        parent_id = _.get(dt, 'parent_id');
                    } else {
                        parent_id = _.get(dt, 'content_group_id');
                    }

                    let tid = `g_${parent_id}`;

                    this.refreshCurrentNode(tid);
                    this.handleClearSelect();
                }).catch(e => {

                });
            },
            handleCancelEdit() {
                this.actionType = 'view';
            },
            async handleMenuUp(it) {
                let isGroup = this.isGroup(it);
                let id = it.id;
                let ret = null;

                if(isGroup) {
                    ret = await this.$japi.group.groupMoveUp(id);
                } else {
                    ret = await this.$japi.menu.menuMoveUp(id);
                }
                if(ret) {
                    this.refreshParentNode(it);
                }
            },
            async handleMenuDown(it) {
                let isGroup = this.isGroup(it);
                let id = it.id;
                let ret = null;

                if(isGroup) {
                    ret = await this.$japi.group.groupMoveDown(id);
                } else {
                    ret = await this.$japi.menu.menuMoveDown(id);
                }

                if(ret) {
                    this.refreshParentNode(it);
                }
            },
            handleDragDrop(node, relaNode, relaPos, evt) {
                //
                let cdata = _.get(node, 'data');
                let rdata = _.get(relaNode, 'data');

                let isGroup = this._isGroup(cdata);
                let isRelaGroup = this._isGroup(rdata);
                let relaId = -1;
                let dataId = null;

                if(!cdata) return;

                if(isRelaGroup) {
                    relaId = _.get(rdata, 'group_id');
                } else {
                    relaId = _.get(rdata, 'content_id');
                }

                if(isGroup) {
                    dataId = _.get(cdata, 'group_id');
                    this.$japi.group.changeDir(dataId, relaId, relaPos, isRelaGroup);
                } else {
                    dataId = _.get(cdata, 'content_id');
                    this.$japi.menu.changeDir(dataId, relaId, relaPos, isRelaGroup);
                }
                console.log(node, lastNode, relaPos, evt);
            },
            handleCancel() {
                this.actionType = 'view';
            },
            handleSuccess(tid) {
                this.refreshCurrentNode(tid);
            }
        }
    }
</script>

<style lang="scss" scoped>
    .menu-custom-tree {
        padding-top: 5px;
    }
    .menu-custom-tree-node {
        width: 100%;
        position: relative;

        .btn-up, .btn-down {
            position: absolute;
            top: 0px;
            right: 5px;
            font-size: 12px;
            background: #DDD;
            color: #999;
            width: 16px;
            height: 16px;
            -webkit-border-radius: 50%;
            -moz-border-radius: 50%;
            border-radius: 50%;
            text-align: center;
            line-height: 16px;
            display: none;

            &:hover {
                color: #333;
                background: #CCC;
            }
        }
        .btn-up {
            right: 24px;
        }

        &:hover {
            .btn-up, .btn-down {
                display: block;
            }
        }
    }
    .mb-wrap .mb-info .info {
        overflow-y: auto;
    }
</style>
